package com.atguigu.gmall.cart.repository;

import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.model.cart.entity.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class CartRepository {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public boolean isExit(String key, Long skuId) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        return cart.hasKey(key, skuId.toString());
    }

    public CartInfo one(String key, Long skuId) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        String cartInfoStr =
                cart.get(key, skuId.toString());
        if (StringUtils.hasText(cartInfoStr)) {
            return JSONs.stringToObj(cartInfoStr, CartInfo.class);
        }
        return null;
    }

    public void save(String key, Long skuId, CartInfo cartItem) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        //设置商品的时候或者CartInfo的setNUm方法里面判断是否超过单个商品数量限制
        if (cartItem.getSkuNum() > RedisConstant.REDIS_CART_SKUNUM) {
            throw new GmallException(ResultCodeEnum.CART_NUM_ERROR);
        }
        cart.put(key, skuId.toString(), JSONs.objecttoString(cartItem));

    }

    public List<CartInfo> list(String key) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        List<CartInfo> list = cart.values(key).stream()
                .map(item -> JSONs.stringToObj(item, CartInfo.class))
                .sorted((o1,o2)->o2.getCreateTime().compareTo(o1.getCreateTime()))
                .collect(Collectors.toList());
        return list;
    }

    public void delete(String key, String... skuIds) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        cart.delete(key, skuIds);
    }


    public Long getTtlByKey(String key) {
        return stringRedisTemplate.getExpire(key);
    }

    public void setTtl(String key, Duration timeout) {
        stringRedisTemplate.expire(key, timeout);
    }

    public Long size(String key) {
        HashOperations<String, String, String> cart = stringRedisTemplate.opsForHash();
        return cart.size(key);
    }
}
